package com.junlong0716.enjoylearning.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.RelativeSizeSpan
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import com.afollestad.materialdialogs.MaterialDialog
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.github.mikephil.charting.charts.BarLineChartBase
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import com.github.mikephil.charting.formatter.IValueFormatter
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet
import com.junlong0716.enjoylearning.R
import com.junlong0716.enjoylearning.adapter.StudyNotesAdapter
import com.junlong0716.enjoylearning.constant.NetConstant
import com.junlong0716.enjoylearning.dialog.DeleteDialog
import com.junlong0716.enjoylearning.dialog.LoadingDialog
import com.junlong0716.enjoylearning.entity.StudyNoteEntity
import com.junlong0716.enjoylearning.entity.rxevent.ChangeTabEvent
import com.junlong0716.enjoylearning.entity.rxevent.RefreshNote
import com.junlong0716.enjoylearning.net.api.NetApi
import com.junlong0716.getknowledgedemo.decoration.DividerItemNoEndDecoration
import com.junlong0716.module.common.base.BaseFragment
import com.junlong0716.module.common.rxbus.Subscribe
import com.junlong0716.module.common.rxbus.ThreadMode
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import org.json.JSONObject
import java.text.DecimalFormat

/**
 *@author: 巴黎没有摩天轮Li
 *@description:
 *@date: Created in 下午10:03 2018/5/8
 *@modified by:
 */
class StudyRecordFragment : BaseFragment<StudyRecordPresenter>(), StudyRecordContract.View, BaseQuickAdapter.RequestLoadMoreListener {
    private lateinit var notesData: ArrayList<StudyNoteEntity>
    private lateinit var studyNotesAdapter: StudyNotesAdapter
    private lateinit var lineChart: LineChart
    private lateinit var mRefreshLayout: SmartRefreshLayout
    private val quarters = ArrayList<String>()
    val entryList = ArrayList<Entry>()
    private lateinit var tvTotalTime: TextView
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun eventBus(s: ChangeTabEvent) {
        if (s.code == 0xbbfa) {
            mPresenter!!.requestStudyNote(this,1,10)
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun eventBus(s: RefreshNote) {
        mRefreshLayout.autoRefresh()
    }

    override fun getLayoutId(): Int = R.layout.fragment_study_record

    override fun initViews(mRootView: View?) {
        notesData = ArrayList()
        val rvList = mRootView!!.findViewById<RecyclerView>(R.id.rl_study_record)
        mRefreshLayout = mRootView.findViewById(R.id.srl_refresh)
        mRefreshLayout.isEnableLoadMore = false
        rvList.layoutManager = LinearLayoutManager(activity)
        studyNotesAdapter = StudyNotesAdapter(notesData, R.layout.item_study_notes)
        rvList.adapter = studyNotesAdapter
        studyNotesAdapter.setHeaderAndEmpty(true)
        rvList.addItemDecoration(DividerItemNoEndDecoration(activity!!.applicationContext, LinearLayoutManager.VERTICAL, 30, ContextCompat.getColor(activity!!, R.color.recyclerview_divider_gray)))
        setOnRecyclerViewScrollDirectListener(rvList)
        //studyNotesAdapter.setOnLoadMoreListener(this, rvList)
        studyNotesAdapter.emptyView = LayoutInflater.from(activity).inflate(R.layout.view_empty, null)
        initHeader()
        mRefreshLayout.setOnRefreshListener {
            mPresenter!!.requestQueryMyStudyTime(this)
            mPresenter!!.requestStudyNote(this,1,10)
        }


//        studyNotesAdapter.setOnItemLongClickListener { adapter, view, position ->
//            DeleteDialog(this.activity!!, object : DeleteDialog.DeleteCallback {
//                override fun onDeleteCallback(dialog: DeleteDialog) {
//                    val loadingDialog = LoadingDialog(this@StudyRecordFragment.activity!!)
//                    loadingDialog.show()
//                    val map = HashMap<String, Int>()
//                    map["id"] = notesData[position].id
//                    val json = JSONObject(map)
//                    OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_DELETE_NOTE)
//                            .tag(this@StudyRecordFragment)
//                            .upJson(json)
//                            .execute(object : StringCallback() {
//                                override fun onSuccess(response: Response<String>?) {
//                                    val jsonObj = JSONObject(response!!.body())
//                                    val code = jsonObj.getString("code")
//                                    if (code == "200") {
//                                        dialog.dismiss()
//                                        loadingDialog.dismiss()
//                                        mRefreshLayout.autoRefresh()
//                                    }
//                                }
//                            })
//                }
//            }).show()
//            return@setOnItemLongClickListener true
//        }

        studyNotesAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view!!.id) {
                R.id.ll_knowledge_content -> {
                    val intent = Intent()
                    intent.setClass(activity, WebActivity::class.java)
                    intent.putExtra("document_url", "http://123.127.109.109:8090/file/temp/a/page1.html")
                    intent.putExtra("document_title", notesData[position].knowledgeTitle)
                    intent.putExtra("document_id", notesData[position].knowledgeId)
                    activity!!.startActivity(intent)
                }

                R.id.tv_delete -> {
                    MaterialDialog.Builder(activity!!)
                            .title("是否删除？")
                            .canceledOnTouchOutside(false)
                            .positiveText("是")
                            .negativeText("否")
                            .onPositive { dialog, which ->
                                requestDelNote(position)
                            }
                            .onNegative { dialog, which ->
                                dialog.dismiss()
                            }
                            .show()
                }
                R.id.tv_edit -> {
                    val intent = Intent(activity, AddNoteActivity::class.java)
                    intent.putExtra("WEB_ID", notesData[position].knowledgeId)
                    intent.putExtra("SELECT_TEXT", notesData[position].remarks)
                    intent.putExtra("IS_UPDATE_NOTE", true)
                    intent.putExtra("NOTES_CONTENT", notesData[position].noteContent)
                    intent.putExtra("NOTES_ID", notesData[position].id)
                    startActivity(intent)
                }
            }
        }
    }

    private fun requestDelNote(position: Int) {
        val map = HashMap<String, Int>()
        map["id"] = notesData[position].id
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_DEL_NOTE)
                .tag(this)
                .upJson(JSONObject(map))
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val jsonObject = JSONObject(response!!.body())
                        if (jsonObject.getString("code") == "200") {
                            ToastUtils.showShort("删除成功！")
                            mRefreshLayout.autoRefresh()
                        }
                    }

                    override fun onError(response: Response<String>?) {

                        ToastUtils.showShort("删除失败！")
                    }
                })
    }

    @SuppressLint("InflateParams")
    private fun initHeader() {
        val studyTimeHeaderView = LayoutInflater.from(activity).inflate(R.layout.item_line_chart_study_time, null)
        lineChart = studyTimeHeaderView.findViewById(R.id.lineChart)
        //initChartView()
        studyNotesAdapter.addHeaderView(studyTimeHeaderView, 0)
//        val addNotesView = LayoutInflater.from(activity).inflate(R.layout.item_add_notes, null)
//        studyNotesAdapter.addHeaderView(addNotesView, 1)
        tvTotalTime = studyTimeHeaderView.findViewById(R.id.tv_total_time)
    }

    private fun initChartView() {
        val mLineChart = lineChart as BarLineChartBase<*>
        val valueFormatter = IAxisValueFormatter { value, axis -> quarters[value.toInt()] }
        //设置说明
        mLineChart.description = null
        //设置图例关
        mLineChart.legend.isEnabled = false
        //设置显示范围
        mLineChart.setVisibleXRangeMaximum(7f)
        mLineChart.setVisibleYRangeMinimum(10f, YAxis.AxisDependency.LEFT)
        //设置透明度
        mLineChart.alpha = 1.0f
        //设置背景色
        mLineChart.setBackgroundColor(Color.WHITE)
        //设置边框
        mLineChart.setBorderColor(Color.rgb(0, 0, 0));
        mLineChart.setGridBackgroundColor(R.color.colorPrimary)
        //设置触摸(关闭影响下面3个属性)
        mLineChart.setTouchEnabled(false)
        //设置是否可以拖拽
        mLineChart.isDragEnabled = true
        //设置是否可以缩放
        mLineChart.setScaleEnabled(true)
        //设置是否能扩大扩小
        mLineChart.setPinchZoom(true)
        //获取X轴
        val xl = mLineChart.xAxis
        //启用X轴
        xl.isEnabled = true
        //设置X轴避免图表或屏幕的边缘的第一个和最后一个轴中的标签条目被裁剪
        xl.setAvoidFirstLastClipping(true)
        //设置X轴底部显示
        xl.position = XAxis.XAxisPosition.BOTTOM
        //设置竖网格
        xl.setDrawGridLines(false)
        //设置X轴文字大小
        xl.textSize = 10f
        //设置X轴单位间隔
        xl.granularity = 1f
        //设置X轴值
        xl.valueFormatter = valueFormatter
        //获取Y轴(左)
        val yl = mLineChart.axisLeft
        //设置Y轴文字在外部显示
        yl.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
        //Y轴字体
        yl.textSize = 10f
        //设置Y轴最大值
        //yl.axisMaximum = 20f
        //设置Y轴起始值
        yl.axisMinimum = 0f
        yl.isEnabled = false
        yl.valueFormatter = IAxisValueFormatter { value, axis -> "${value}分" }
        //获取Y轴(右)
        val yl2 = mLineChart.axisRight
        //禁用右侧Y轴
        yl2.isEnabled = false
        //数据


        val l1 = LineDataSet(entryList, "红色")
        l1.valueFormatter = IValueFormatter { value, entry, dataSetIndex, viewPortHandler ->
            val df = DecimalFormat("")
            df.format(value.toInt()) + "分钟"
        }
        l1.axisDependency = YAxis.AxisDependency.LEFT
        //设置包括的范围区域填充颜色
        l1.setDrawFilled(true)
        //设置线的宽度
        l1.lineWidth = 1f
        //设置曲线的颜色
        l1.color = ContextCompat.getColor(activity!!, R.color.colorAccent)
        //设置曲率,0.05f-1f  1为折线
        l1.cubicIntensity = 0.1f
        l1.mode = LineDataSet.Mode.HORIZONTAL_BEZIER
        //设置有圆点
        l1.setDrawCircles(true)
        //设置小圆点的大小
        l1.circleRadius = 3f
        l1.valueTextSize = (10f)
        //设置圆圈颜色
        l1.setCircleColor(ContextCompat.getColor(activity!!, R.color.colorAccent))
        //填充圆圈内颜色
        l1.setCircleColorHole(Color.rgb(255, 255, 255))
        //设置不显示数值
        l1.setDrawValues(true)
        val lineDataSetArrayList = ArrayList<ILineDataSet>()
        lineDataSetArrayList.add(l1)
        val lineData = LineData(lineDataSetArrayList)
        mLineChart.data = lineData
        //设置XY轴进入动画
        mLineChart.animateXY(800, 800)
        //设置最小的缩放
        mLineChart.setScaleMinima(1f, 1f)
    }

    override fun lazyFetchData() {
        mRefreshLayout.autoRefresh()
    }

    override fun attachPresenter() {
        mPresenter = StudyRecordPresenter()
        mPresenter!!.attachView(this)
    }

    override fun onLoadMoreRequested() {
        studyNotesAdapter.loadMoreEnd()
    }

    override fun requestStudyNoteSucceed(noteData: ArrayList<StudyNoteEntity>) {
        mRefreshLayout.finishRefresh()
        notesData.clear()

        if (noteData.isEmpty()) {
            notesData.clear()
            studyNotesAdapter.notifyDataSetChanged()
            return
        }

        if (noteData.size >= 5) {
            notesData.add(noteData[0])
            notesData.add(noteData[1])
            notesData.add(noteData[2])
            notesData.add(noteData[3])
            notesData.add(noteData[4])
        } else {
            notesData.addAll(noteData)
        }


        val footerView = LayoutInflater.from(activity).inflate(R.layout.item_footer_see_all, null)

        studyNotesAdapter.removeAllFooterView()
        studyNotesAdapter.addFooterView(footerView)
        studyNotesAdapter.notifyDataSetChanged()


        val tvSeeAll = footerView.findViewById<TextView>(R.id.tv_see_all)
        tvSeeAll.setOnClickListener {
            go(NoteActivity::class.java)
        }
    }

    override fun requestQueryMyStudyTimeSucceed(dayList: ArrayList<String>, totalTime: String) {
        quarters.clear()
        entryList.clear()
        for (i in 0 until dayList.size) {
            val date = dayList[i].split("|")[0]
            if (i == 6) {
                quarters.add("今天")
            } else {
                quarters.add(date.substring(5, 10))
            }

            val time = dayList[i].split("|")[1]
            entryList.add(Entry(i.toFloat(), time.toFloat()))

        }
        val ss = SpannableString("总学习时长\t${totalTime}\t小时")
        //ss.setSpan(TypefaceSpan("default"), 5, 5 + totalTime.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        ss.setSpan(RelativeSizeSpan(1.6f), 6, 7 + totalTime.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        ss.setSpan(ForegroundColorSpan(ContextCompat.getColor(activity!!,R.color.colorPrimary)), 6, 7 + totalTime.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        tvTotalTime.text = ss
        initChartView()
    }
}